package dependenciesIO;

import java.io.FileWriter;
import java.util.ArrayList;
import java.util.HashMap;

import customization.Constants;
import download.DownloadManager;
import download.WebFunction;

public class DependencyModule {

	public static final void intraSiteDependencies(String site, FileWriter fOut) throws Exception {
		/************************/
		/** initialization **/
		/************************/
		/** prepare the set of pairs IO */
		HashMap<String, WebFunction> clusterForMB=DownloadManager.stubs.get(site);
	
		
		ArrayList<WebFunction> newFunctionsWithSamples= new ArrayList<WebFunction>();
		ArrayList<WebFunction> toProbeFunctions= new ArrayList<WebFunction>();
		
		
		for(WebFunction f: clusterForMB.values()){
			if(f.validInputs!=null && f.validInputs.size()>=Constants.lowerSetSizeForStatistics){
				newFunctionsWithSamples.add(f);
				System.out.println();
			}
			else {
				toProbeFunctions.add(f);
			}
		}
	
		/************************/
		/** loop **/
		/************************/
		/** as long as we do not have an object dependency for every function, we have to add new such objects  **/
		ArrayList<DependentFunctions> dependencies=DependencyModule.computeIntraSiteIODependencies(newFunctionsWithSamples,toProbeFunctions);
		for(DependentFunctions f: dependencies){
			fOut.append(f.toString());
		}
		
	}

	public static ArrayList<DependentFunctions> computeIntraSiteIODependencies(ArrayList<WebFunction> functionsWithKnownInputs, ArrayList<WebFunction> toProbeFunctions) throws Exception{
		ArrayList<DependentFunctions> dependecies= new ArrayList<DependentFunctions>();
		
		for(WebFunction F1: functionsWithKnownInputs){
			
			DependentFunctions fd=new DependentFunctions(F1.validInputs, F1);
			fd.initPathGuide();
			/**System.out.println(fd.paths.toString()); **/
			
			fd.computePathsWithValidInputsForSecondFunction(toProbeFunctions);  
			dependecies.add(fd);
		}
		return dependecies;
	}
	
	public static void main(String[] args) throws Exception
    {  
    	  	/** DownloadManager.writeFunctionsAndTheirSitesToFile(Constants.fileWithTheInputTypesOfTheFunctions);**/
		DownloadManager.initStubs();
		
		
		ArrayList<WebFunction> listF=DownloadManager.computeSamplesForFunctionsWithKnownTypes();
		System.out.println("Functions with known inputs:");
		for(WebFunction F: listF){
			System.out.print(F.functionName+"   ");	
		}
		System.out.println();
		
		/** prepare the output file for dependencies **/
		FileWriter fOut = new FileWriter(Constants.fileIODependencies);
		
		if(Constants.filterWorkingSet){
			for(String site: Constants.workingSetWebSites){
				DependencyModule.intraSiteDependencies(site, fOut);
			}
		}
		fOut.close();
		DownloadManager.storeCacheOnDisk();
    }

}
